from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django_redis import get_redis_connection
from decimal import Decimal
from goods.models import SKU
from .serialziers import OrederSettlementSerialzier,SaveOderSerialiuzer


# Create your views here.

class OderSettlementView(APIView):
    """
    訂單結算視圖
    """

    permission_classes = [IsAuthenticated]

    # 設置權限　用戶需要登陸才能訪問

    def get(self, request):
        """
        獲取
        :param request:
        :return:
        """
        # 獲取當前登陸用戶
        user = request.user
        # 從數據庫中獲取數據

        redis_conn = get_redis_connection("cart")

        cart_redis = redis_conn.hgetall("cart_%s" % user.id)
        # hgetall 查詢嘻哈數據不存在返回列表
        # haetall 查詢數據存在返回所有的域和值　以列表的形式
        cart_selected = redis_conn.smembers("cart_selected_%s" % user.id)
        # smembers 查詢集合，如果存在返回集合所有成員，不存在返回空集合

        cart = {}

        for sku_id in cart_selected:
            cart[int(sku_id)] = int(cart_redis[sku_id])

        # 查詢商品jiesuan

        skus = SKU.objects.filter(id__in=cart.keys())

        for sku in skus:
            sku.count = cart[sku.id]

        # 運費
        freight = Decimal("10.00")

        serialzier = OrederSettlementSerialzier({"freight": freight, "skus": skus})
        return Response(serialzier.data)

class SaveOderView(CreateAPIView):
    """
    保存訂單
    """
    pagination_class = [IsAuthenticated]
    serializer_class = SaveOderSerialiuzer

